﻿using System.Globalization;
using Avalonia.Controls;
using Avalonia.Interactivity;
using LuckyFish.CalculatorLib;

namespace LuckyFish.CalculatorFluent.Pages;

public partial class HomeView : UserControl
{
    public HomeView()
    {
        InitializeComponent();
    }
    
    private void ButtonClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Button control) return;
        if (control.Tag is not string s) return;
        switch (s)
        {
            case "Clear":
                NowBlock.Text = "0";
                break;
            case "Delete":
                NowBlock.Text = NowBlock.Text!.Length <= 1 ? "0" : NowBlock.Text?.Remove(NowBlock.Text.Length - 1);
                break;
            case "=":
                string str;
                try
                {
                    var re = ReversePolishCalculator.Calculator(NowBlock.Text);
                    str = re.ToString(CultureInfo.InvariantCulture);
                }
                catch
                {
                    str = "有误";
                }
                (NowBlock.Text, HistoryBlock.Text) = (str, NowBlock.Text);
                break;
            default:
                if (NowBlock.Text == "0") NowBlock.Text = "";
                NowBlock.Text += s;
                break;
        }
    }

    private async void CopyClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(NowBlock.Text) || NowBlock.Text == "0")return;
        var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
        await clipboard?.SetTextAsync(NowBlock.Text)!;
    }

    private void ChangeNowClick(object? sender, RoutedEventArgs e)
    {
        if(NowBlock.Text == HistoryBlock.Text)return;
        NowBlock.Text = HistoryBlock.Text;
        HistoryBlock.Text = "0";
    }
    
}